package com.elookinto.sample;

import com.sun.jersey.spi.container.servlet.ServletContainer;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.apache.felix.http.api.ExtHttpService;
import org.osgi.service.http.NamespaceException;

public class JerseyServletRegistration {

    private ExtHttpService extHttpService;
    private ServletContainer jerseyServlet;
    private final static Logger LOGGER = Logger.getLogger(JerseyServletRegistration.class.getName());

    public void init() {
        jerseyServlet = new ServletContainer();
        registerServlets();
    }

    public void destroy() {
        if (this.extHttpService != null) {
            extHttpService.unregisterServlet(jerseyServlet);
        }
    }

    private void registerServlets() {
        if (extHttpService != null) {
            try {
                LOGGER.info("Registering  sample sevelet");
                extHttpService.registerServlet("/sample", jerseyServlet, getJerseyServletParams(), null);
            } catch (ServletException se) {
                LOGGER.severe("Servlet Exception thrown while registering Jersey Servlet to OSGI HTTP Service");
            } catch (NamespaceException se) {
                LOGGER.severe("Namespace Exception thrown while registering Jersey Servlet to OSGI HTTP Service" + se);
            }
        } else {
            LOGGER.severe("Jsersey Servlet cannot be registered since ExtHttpService is not available!");
        }

    }

    private Dictionary<String, String> getJerseyServletParams() {
        Dictionary<String, String> jerseyServletParams = new Hashtable<String, String>();
        jerseyServletParams.put("javax.ws.rs.Application", JerseyApplication.class.getName());
        setCommonJerseyServletParams(jerseyServletParams);
        return jerseyServletParams;
    }

    private Dictionary<String, String> setCommonJerseyServletParams(Dictionary<String, String> jerseyServletParams) {
        jerseyServletParams.put("com.sun.jersey.spi.container.ContainerRequestFilters", MediaTypeFilter.class.getName());
        jerseyServletParams.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
        return jerseyServletParams;
    }

    public void setExtHttpService(ExtHttpService extHttpService) {
        this.extHttpService = extHttpService;
    }
}
